<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/11
 * Time: 17:05
 */

namespace app\api\controller;

use app\api\BaseController;
use app\common\model\QuestionOption;
use app\common\model\Equipment as EquipmentModel;
use app\common\model\Refundreturn;
use app\common\logic\Buy;

/**
 * @title 设备库控制器
 */
class Equipment extends BaseController
{

    /**
     * @title 客户端---服务单订单列表
     * @description
     * @author zjw
     * @url /Equipment/select
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
        0：待审核    （前端提交完设备待审核）
        1：待支付    （后台审核通过，未付款）
        2：进行中    （已付款，待派单，待服务，待出发，已出发，已到达，服务中）
        3：已完成    （取消，服务完成，评价，申请发票）
        待审核：order_state == 1
        待派单：order_state == 3
        待服务：service_state == 1
        待出发：service_state == 1
        服务中：service_state == 3
        已出发：service_state == 2
        已到达：service_state == 3
        已完成：service_state == 4
        已评价：evaluation_state == 1
        已取消：order_state == -1
     * @param string order_sn 订单编号(搜索)
     * @param string query_start_date 开始时间(搜索)
     * @param string query_end_date 结束时间(搜索)
     * @param string state_type 订单状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function select()
    {
        $order_status = input('order_status', '-1');   //-1:全部 

        //公共条件
        $params['member_id'] = $this->user_id;
        $params['delete_state'] = 0;
        $params['lock_state'] = 0;
        $params['parent_id'] = 0;
        $params['order_source'] = ['neq', 2];
        // $params['service_type'] = 1; 


        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;

        if ($order_status == '-1') {
            // $params['order_state'] = array('neq','2');  #主单状态
            $s_order_list = db('s_order')->alias('so')
                ->where($params)
                ->order('so.add_time', 'desc')
                ->limit($offset, $pagesize)
                ->select();
        } else {
            //判断状态
            switch ($order_status) {
                case  0:   #待审核  
                    $params['order_state'] = array('eq', '1');  #主单状态
                    break;
                case  1:   #待支付  
                    $params['order_state'] = 2;
                    break;
                case  2:   #进行中 
                    $params['order_state'] = array('in', '2,3,7,8');
                    break;
                case  3:   #已完成
                    $params['order_state'] = array('in', '-1,0,4,5,6');
                    break;
                default:
                    break;
            }
            $s_order_list = db('s_order')->alias('so')
                ->where($params)
                ->order('so.add_time', 'desc')
                ->limit($offset, $pagesize)
                ->select();
        }

        if (empty($s_order_list)) {
            $s_order_list = array();
            json_success_return($s_order_list);
        }

        //获取信息
        foreach ($s_order_list as $key => $value) {
            //获取主单里包含几个商品
            $s_order_list[$key]['count'] = db('s_order_detail')->where(['order_id' => $value['order_id']])->count();
            $s_order_list[$key]['order_type_text'] = getSorderText($value['order_type']);
            $s_order_list[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $s_order_list[$key]['order_state_text'] = getSorderStatusText($value['order_state']);

            #如果该订单已指派，返回服务人员信息
            $s_order_list[$key]['mechanic_type'] = '';
            if (!empty($value['assign_mechanic_id'])) {
                $mechanic_info = db('fuwu_personal')->where(['id' => $value['assign_mechanic_id']])->find();
                $s_order_list[$key]['mechanic_type'] = '企业';
                if ($mechanic_info['prevtype'] == 4) {
                    $s_order_list[$key]['mechanic_type'] = '个人';
                }
            }

            #返回发票的状态
            switch ($value['service_invoice_status']) {
                case 0:
                    $s_order_list[$key]['type'] = '0';
                    $s_order_list[$key]['msg'] = '未申请';
                    break;
                case 1:
                    $s_order_list[$key]['type'] = '1';
                    $s_order_list[$key]['msg'] = '待审核';
                    break;
                case 2:
                    $s_order_list[$key]['type'] = '2';
                    $s_order_list[$key]['msg'] = $value['service_invoice_reasons'];
                    break;
                case 3:
                    $s_order_list[$key]['type'] = '3';
                    break;
                default:
                    break;
            }
        }
        json_success_return($s_order_list);
    }

    /**
     * @title 客户端---服务主订单详情
     * @description
     * @author zjw
     * @url /Equipment/detail
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @return {"code":200,"msg":"succeess"}
     */
    public function detail()
    {

        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            return json_fail_return('该订单不存在');
        }
        //1、获取主单详情
        $s_order_list['order_list'] = db('s_order')->where('member_id', $this->user_id)->where('order_id', $order_id)->find();
        $s_order_list['order_list']['order_type_text'] = getSorderText($s_order_list['order_list']['order_type']);
        $s_order_list['order_list']['appointment_time'] = date('Y-m-d H:i', $s_order_list['order_list']['appointment_unix_time']);

        $s_order_list['order_list']['add_time'] = date('Y-m-d H:i', $s_order_list['order_list']['add_time']);

        #获取预约人姓名
        $member_info = db('address')->where(['address_id' => $s_order_list['order_list']['address_id']])->find();
        $member_name = empty($member_info['address_realname']) ? '未设置' : $member_info['address_realname'];
        $s_order_list['order_list']['member_name'] = $member_name;



        #返回发票的状态
        switch ($s_order_list['order_list']['service_invoice_status']) {
            case 0:
                $s_order_list['order_list']['type'] = '0';
                $s_order_list['order_list']['msg'] = '未申请';
                break;
            case 1:
                $s_order_list['order_list']['type'] = '1';
                $s_order_list['order_list']['msg'] = '待审核';
                break;
            case 2:
                $s_order_list['order_list']['type'] = '2';
                $s_order_list['order_list']['msg'] = $s_order_list['order_list']['service_invoice_reasons'];
                break;
            case 3:
                $s_order_list['order_list']['type'] = '3';
                break;
            default:
                break;
        }
        // p($s_order_list);die;
        if (empty($s_order_list)) {
            json_fail_return('订单id信息错误');
        }

        # 获取主单下面的所有设备
        $zhu_goods_list = db('s_order_detail')->where('order_id', $order_id)->select();

        foreach ($zhu_goods_list as $key => $value) {
            $s_order_list['order_list']['goods_list'][$key]['goods_name'] = $value['goods_name'];
            $s_order_list['order_list']['goods_list'][$key]['b_name'] = $value['b_name'];
            $s_order_list['order_list']['goods_list'][$key]['type_model'] = $value['type_model'];
        }
        $s_order_list['order_list']['count_hours'] = $s_order_list['order_list']['work_master_hous'];

        //2、获取追加单下面的所有设备
        $append_order_list = db('s_order')->where(['parent_id' => $order_id, 'member_id' => $this->user_id])->select();

        # 获取追加订单下面所有的设备
        $s_order_list['order_list']['append_goods_list'] = [];
        foreach ($append_order_list as $key => $value) {
            #获取追加订单设备详情
            $append_goods_list = db('s_order_detail')->where('order_id', $value['order_id'])->select();

            foreach ($append_goods_list as $k => $v) {
                $item = [
                    'son_order_id' => $value['order_id'],
                    'order_amount' => $value['order_amount'],
                    'order_state' => $value['order_state'],
                    'order_text' => getSorderStatus($value['order_state']),
                    'goods_name' => $v['goods_name'],
                    'b_name' => $v['b_name'],
                    'type_model' => $v['type_model'],
                    'examine_failed_reason' => $value['examine_failed_reason']
                ];
                array_push($s_order_list['order_list']['append_goods_list'], $item);
            }
        }

        //3、获取追加工时的所有信息
        $s_order_list['order_list']['append_order_hours'] = [];
        $append_order_hours = db('s_order_append')->where(['order_id' => $order_id])->select();
        foreach ($append_order_hours as $key => $value) {
            //获取服务人员信息
            $originator_info = db('fuwu_personal')->where(['id' => $value['originator']])->find();

            $s_order_list['order_list']['append_order_hours'][$key]['originator'] = $originator_info['name'];
            #判断是前台追加还是后台追加
            if ($value['originator'] == 0) {
                $s_order_list['order_list']['append_order_hours'][$key]['originator'] = '管理员';
            }

            $s_order_list['order_list']['append_order_hours'][$key]['hours_id'] = $value['id'];
            $s_order_list['order_list']['append_order_hours'][$key]['add_hours'] = $value['add_hours'];
            $s_order_list['order_list']['append_order_hours'][$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            $s_order_list['order_list']['append_order_hours'][$key]['fail_reason'] = $value['fail_reason'];
            #支付状态
            $s_order_list['order_list']['append_order_hours'][$key]['status'] = $value['status'];
            #审核状态
            $s_order_list['order_list']['append_order_hours'][$key]['audit_status'] = $value['audit_status'];
            $s_order_list['order_list']['append_order_hours'][$key]['hours_price'] = number_format($value['payper_hour'] * $value['add_hours'], 2);
        }

        //4、获取更换人员记录
        $s_order_list['order_list']['change_personal'] = [];
        $change_order_personal = db('s_order_change')->where(['order_id' => $order_id])->select();
        foreach ($change_order_personal as $key => $value) {
            $s_order_list['order_list']['change_personal'][$key]['refusal_reason'] = $value['refusal_reason'];
            $s_order_list['order_list']['change_personal'][$key]['c_time'] = date('Y-m-d H:i:s', $value['c_time']);
            $s_order_list['order_list']['change_personal'][$key]['refusal_remake'] = $value['refusal_remake'];
            $s_order_list['order_list']['change_personal'][$key]['fail_reason'] = $value['fail_reason'];
            #审核状态
            $s_order_list['order_list']['change_personal'][$key]['status'] = $value['status'];
        }

        //5、获取服务人员信息
        $s_order_list['order_list']['service_info'] = [];
        if (!empty($s_order_list['order_list']['assign_mechanic_id'])) {
            $s_order_list['order_list']['service_info'] = db('fuwu_personal')->where(['id' => $s_order_list['order_list']['assign_mechanic_id']])->field('avtar,name,prevtype,phone')->find();

            $s_order_list['order_list']['service_info']['mechanic_type'] = '企业';
            if ($s_order_list['order_list']['service_info']['prevtype'] == 4) {
                $s_order_list['order_list']['service_info']['mechanic_type'] = '个人';
            }
            #获取评价的综合评分
            $evaluate_info = db('evaluategoods')->where(['geval_frommemberid'=>$s_order_list['order_list']['assign_mechanic_id'],'evaluation_type'=>2])->select();
            $count_star = 0;
            foreach($evaluate_info as $k => $v){
               $star = ($v['geval_attitude'] + $v['geval_technical']+ $v['geval_quality']);
               $count_star += $star; 
            }
            // $s_order_list['order_list']['service_info']['evaluate_star'] = $count_star * count($evaluate_info) / (count($evaluate_info)*15);
            $s_order_list['order_list']['service_info']['evaluate_star'] = 4;  
        }

        json_success_return($s_order_list);
    }

    //获取子订单详情
    public function son_detail()
    {
        $data = input('post.');

        if (empty($data['type'])) {
            json_fail_return('参数错误');
        }

        //根据type来区分是主订单详情 还是 追加订单详情
        $param = [];
        $param['member_id'] = $this->user_id;

        if ($data['type'] == 1) {
            $param['order_id'] = $data['order_id'];  #主订单

            #获取主单下面的所有设备
            $son_goods_info = db('s_order_detail')->where('order_id', $data['order_id'])->select();

            $s_order_list = [];
            foreach ($son_goods_info as $key => $value) {
                //1、获取设备信息
                $s_order_list[$key]['goods_info'] = $value;

                //2、获取每个商品需要的配件
                $parts_list = db('s_order_parts')->where(['detail_order_id' => $value['id']])->select();
                $s_order_list[$key]['part_list'] = [];
                $parts_total = 0; #配件总价
                foreach ($parts_list as $k => $v) {
                    #单个配件的信息
                    $good_info = db('goods')->alias('g')
                        ->join('goodscommon gc', 'gc.goods_commonid = g.goods_commonid')
                        ->where(['goods_id' => $v['good_id']])
                        ->find();
                    #配件名称
                    $s_order_list[$key]['part_list'][$k]['part_name'] = $good_info['goods_name'] . ' ' . $good_info['spec_values'];
                    #配件品牌
                    $s_order_list[$key]['part_list'][$k]['brand_name'] = $good_info['brand_name'];
                    // #配件规格型号
                    // $s_order_list[$key]['part_list'][$k]['spec_values'] = $good_info['spec_values'];
                    #配件单价
                    $s_order_list[$key]['part_list'][$k]['technician_price'] = $v['sale_part_price'];
                    #配件数量
                    $s_order_list[$key]['part_list'][$k]['part_num'] = $v['num'];
                    #是否带货 0--不需要 1--需要
                    $s_order_list[$key]['part_list'][$k]['is_bring_goods'] = $v['is_bring_goods'];
                    #配件总价
                    $parts_total  += $v['num'] * $v['sale_part_price'];
                }
                $s_order_list[$key]['parts_total'] = number_format($parts_total, 2);

                //3、获取图片
                $s_order_list[$key]['img_list'] = db('s_order_image')->where(['order_detail_id' => $value['id']])->select();
                foreach ($s_order_list[$key]['img_list'] as $k => $v) {
                    $s_order_list[$key]['img_list'][$k]['src'] = $v['src'];
                }

                //4、获取环境配置
                $s_order_list[$key]['science_list'] = [];
                if (!empty($value['scienceIds'])) {
                    $scienceIds_array = explode(',', $value['scienceIds']);
                    foreach ($scienceIds_array as $k => $v) {
                        $s_order_list[$key]['science_list'][$k] = db('equipment_science')->where(['id' => $v])->find();
                    }
                }
                //5、获取部位
                $s_order_list[$key]['option_list'] = [];
                if (!empty($value['option_info'])) {
                    $option_list = json_decode($value['option_info'], true);
                    foreach ($option_list as $k => $v) {
                        $s_order_list[$key]['option_list'][] =  db('equipment_option')->where(['id' => $v['oid']])->find();
                        $s_order_list[$key]['option_list'][$k]['selected'] = $v['selected'];
                    }
                }
            }
        } else {
            $param['parent_id'] = $data['order_id']; #追加订单

            #获取所有追加的订单信息
            $append_order_list = db('s_order')->where($param)->select();

            $equipment_list = []; #返回返回设备
            #遍历所有追加订单，获取每个订单下的所有设备
            foreach ($append_order_list as $key => $value) {

                #根据追加订单的订单id获取所有设备详情
                $append_goods_list = db('s_order_detail')->where('order_id', $value['order_id'])->select();

                foreach ($append_goods_list as $k => $v) {
                    $equipment_item = [];

                    //1、获取每个设备的详情
                    $v['append_door_fee'] = $value['door_fee']; #追加单上门费
                    $equipment_item['goods_info'] = $v;
                    
                    //2、获取每个商品需要的配件
                    $form_parts_list = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
                    $parts_total = 0; #配件总价
                    $parts_list_append = [];
                    foreach ($form_parts_list as $k => $parts) {
                        #单个配件的信息
                        $good_info = db('goods')->alias('g')
                            ->join('goodscommon gc', 'gc.goods_commonid = g.goods_commonid')
                            ->where(['goods_id' => $parts['good_id']])
                            ->find();

                        $parts_list_append[] = [
                            'part_name' => $good_info['goods_name'],
                            'brand_name' => $good_info['brand_name'],
                            'technician_price' => $parts['sale_part_price'],
                            'part_num' => $parts['num']
                        ];
                        $parts_total  += $parts['num'] * $parts['sale_part_price'];
                    }
                    $equipment_item['part_list'] = $parts_list_append; //配件列表
                    $equipment_item['parts_total'] = $parts_total; //配件总价

                    //3、获取图片
                    $form_img_lists = db('s_order_image')->where(['order_detail_id' => $v['id']])->select();
                    $image_list = [];
                    foreach ($form_img_lists as $k => $img) {
                        $image_list[] = [
                            'id' => $img['id'],
                            'order_detail_id' => $v['id'],
                            'src' => $img['src']
                        ];
                    }
                    $equipment_item['img_list'] = $image_list;

                    //4、获取环境配置
                    $scene_list = [];
                    if (!empty($v['scienceIds'])) {
                        $scienceIds_array = explode(',', $v['scienceIds']);
                        foreach ($scienceIds_array as $kk => $science) {
                            $scene_list[] = db('equipment_science')->where(['id' => $science])->find();
                        }
                    }
                    $equipment_item['science_list'] = $scene_list;

                    //5、获取部位
                    $position_list = [];
                    if (!empty($v['option_info'])) {
                        $option_list = json_decode($v['option_info'], true);
                        foreach ($option_list as $kkk => $option) {
                            $position_list[] =  db('equipment_option')->where(['id' => $option['oid']])->find();
                            $position_list[count($position_list) - 1]['selected'] = $option['selected'];
                        }
                    }
                    $equipment_item['option_list'] = $position_list;
                    $equipment_list[] = $equipment_item;
                }
            }
            $s_order_list = $equipment_list;
        }

        json_success_return($s_order_list);
    }

    /**
     * @title 客户端---服务单设备支付
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author 
     * @url /Equipment/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function pay()
    {
        $data = input('post.');
        $order_id = input('param.order_id');
        $payment_code = input('param.payment_code');
        $memberId = $this->user_id;

        if (empty($order_id)) {
            json_fail_return('参数错误');
        }

        #判断是设备支付还是工时支付
        if ($data['pay_type'] == 1) {
            #设备支付
            #获取服务单详情
            $order_info = db('s_order')->where(['order_id' => $order_id])->find();
            if (empty($order_info)) {
                json_fail_return('暂无支付单信息');
            }

            #优惠劵、积分抵扣
            $result_discount = getPayDiscount($memberId, $data, $order_info['order_amount']);
            $pay_data = [
                'pay_sn' => makePaySn($memberId),
                'payment_code' => $payment_code,
                'payment_time' => time(),
                'order_state' => 3,
                'pay_amount' => $result_discount['integral_price'],
                'voucher_price' => $result_discount['voucher_price'], #优惠劵抵扣了多少钱
                'order_integral' => $result_discount['fina_integral'],
                'order_integral_price' => $result_discount['order_integral_price'] #积分抵扣了多少钱
            ];
            db('s_order')->where(['order_id' => $order_id])->update($pay_data);

            #生成订单缓存表，用于统计数据
            $res_cache  = [
                'order_id' => $order_info['order_id'],
                'order_sn' => $order_info['order_sn'],
                'order_type' => 3,
                'order_add_time' => time(),
                'payment_code' => 1,
                'order_state' => 20,
                'order_amount' => $order_info['order_amount'],
                'evaluation_state' => $order_info['evaluation_state'],
                'order_state' => $order_info['order_state'],
                'refund_state' => $order_info['refund_state'],
                'refund_amount' => $order_info['refund_amount'],
                'order_from' => 2,
                'order_isvalid' => 1,
                'buyer_id' => $order_info['member_id'],
                'buyer_name' => $order_info['member_name'],
            ];
            db('statorder')->insertGetId($res_cache);

            $order_pay['pay_type'] = 1;
        } else {
            #工时支付

            #获取追加工时详情
            $append_info = db('s_order_append')->where(['id' => $order_id])->find();
            if (empty($append_info)) {
                json_fail_return('暂无支付单信息');
            }

            #优惠劵、积分抵扣
            $result_discount = getPayDiscount($memberId, $data, $append_info['hours_total']);

            $pay_data = [
                'pay_sn' => makePaySn($memberId),
                'pay_time' => time(),
                'status' => 2,
            ];
            db('s_order_append')->where(['id' => $order_id])->update($pay_data);
            $order_pay['pay_type'] = 2;
        }

        #生成支付单数据
        $order_model = new \app\common\model\Order();

        $order_pay = array();
        $order_pay['pay_sn'] = $pay_data['pay_sn'];
        $order_pay['buyer_id'] = $memberId;
        $order_pay['api_paystate'] = 1;
        $order_pay['c_time'] = time();
        $order_pay_id = $order_model->addOrderpay($order_pay);

        if (!$order_pay_id) {
            exception('订单保存失败[未生成支付单]');
        }

        return json_success_return();
    }

    //获取设备列表
    public function changeDeveice()
    {
        $data = input('post.');

        $params = [];
        if (!empty($data['goods_name'])) {
            $params['goods_name'] = array('like', '%' . $data['goods_name'] . '%');
        }
        $params['status'] = 1;
        $params['equipment_del'] = 0;
        $params['equipment_status'] = 1;

        // $page = intval(input('page'))?intval(input('page')):1;
        // $pagesize = intval(input('pagesize'))?intval(input('pagesize')):15;
        // $offset = ($page-1)*$pagesize;

        $deveice_list = db('new_equipment')->alias('ne')
            ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
            // ->limit($offset,$pagesize)
            ->where($params)
            ->select();

        #循环了多少次，键值就是几，  二维数组是以小数组来决定的    //判断是几位数组  
        $new = [];
        foreach ($deveice_list as $key => $value) {
            $speci_type = [];
            if (!empty($value['spec_value_type'])) {
                $speci_type = unserialize($value['spec_value_type']); # 获取规格型号
                foreach ($speci_type as $k => $v) {
                    $new[] = [
                        'equipment_brand_id' => $value['equipment_brand_id'],
                        'goods_name' => $value['goods_name'],
                        'brand_name' => $value['brand_name'],
                        'is_question' => 0,
                        'question_id' => $value['question_id'],
                        'specifications' => $v
                    ];
                    if ($value['question_id'] > 0) {
                        $new[count($new) - 1]['is_question'] = 1;
                    }
                }
            } else {
                $new[] = [
                    'equipment_brand_id' => $value['equipment_brand_id'],
                    'goods_name' => $value['goods_name'],
                    'brand_name' => $value['brand_name'],
                    'is_question' => 0,
                    'question_id' => $value['question_id'],
                ];
                if ($value['question_id'] > 0) {
                    $new[count($new) - 1]['is_question'] = 1;
                }
            }
        }

        return json_success_return($new);
    }

    //返回在线诊断
    public function online_diagnosis()
    {

        $parms['status'] = 1;
        $parms['id'] = input('param.question_id');
        $question_list = db('question')->field('id, title,gc_id1,gc_id2,gc_id3,option_id,status')->where($parms)->select();

        #首先获取所有问题的列表，然后再一个问题对应多个答案
        foreach ($question_list as $key => $value) {

            #获取所有下级，找到lev为0的数据为当前数据的答案
            $son_question_list = explode(',', $value['option_id']);

            foreach ($son_question_list as $k => $v) {

                #找到首类数据的答案
                $son_question_info = db('question_option')->field('id, content,parent_id,question_id,answer_id,lev')->where(['id' => $v, 'lev' => 0])->find();
                if (!empty($son_question_info)) {
                    $question_list[$key]['son_question_list'][] = $son_question_info;
                }

                #再判断当前数据有没有下级数据
                $last_son_question_list = db('question_option')->where(['parent_id' => $v])->select();

                if (!empty($last_son_question_list)) {
                    foreach ($last_son_question_list as $kk => $vv) {
                        #获取原因跟处理办法（原因就是诊断结果，处理办法存订单上，可服务人员看的）
                        $answer_info = db('answer')->where(['id' => $vv['answer_id']])->find();
                        $vv['answer'] = $answer_info['content'];
                        $vv['method'] = $answer_info['method'];


                        $question_list[$key]['son_question_list'][$k]['last_son_question_list'][$kk] = $vv;
                    }
                }
            }
        }
        return json_success_return($question_list);
    }

    #根据设备id获取详细信息
    public function getDeviceInformation()
    {
        $equipment_id = input('param.equipment_id'); #设备id
        if (empty($equipment_id)) {
            json_fail_return('参数错误');
        }

        #首先获取设备的主信息
        $device_list = db('new_equipment_brand')->alias('neb')
            ->join('new_equipment ne', 'ne.id = neb.equipment_id')
            ->field('ne.id,ne.goods_name,neb.equipment_brand_id,neb.brand_name,neb.option,neb.science,neb.spec_value_type,ne.gc_id,ne.class_name,ne.gc_one_id,ne.gc_two_id,ne.gc_three_id')
            ->where(['equipment_brand_id' => $equipment_id])->find();

        $device_list['type_model'] = '';
        if (!empty($device_list['spec_value_type'])) {
            $device_list['type_model'] = implode(',', unserialize($device_list['spec_value_type']));
        }

        if (empty($device_list)) {
            json_fail_return('所选商品信息无效');
        }

        #获取部位
        if (!empty($device_list['option'])) {
            $option_array = explode(',', $device_list['option']);
            foreach ($option_array as $key => $value) {
                $option_list = db('equipment_option')->where(['id' => $value])->find();
                if (!empty($option_list)) {
                    $device_list['option_list'][] = $option_list;
                } else {
                    $device_list['option_list'] = array();
                }
            }
        }
        #获取环境配置
        if (!empty($device_list['science'])) {
            $science_array = explode(',', $device_list['science']);
            foreach ($science_array as $key => $value) {
                $science_list = db('equipment_science')->where(['id' => $value])->find();
                if (!empty($science_list)) {
                    $device_list['science_list'][] = $science_list;
                } else {
                    $device_list['science_list'] = array();
                }
            }
        }

        return json_success_return($device_list);
    }


    /**
     * @title 服务单预订单
     * @description
     * @param string ifcart 是否来自购物车1是0否
     * @param string cart_id 商品信息格式id|number
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/prepare
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function equipmentAdvance()
    {

        $order_id = input('order_id');
        $confirm_type = input('confirm_type'); #1--设备 2--追加工时

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        //获取服务单预订单的全部信息
        $buy_logic = new Buy();
        $result = $buy_logic->buyStep1_equipment($this->user_id, $order_id, $confirm_type);

        json_success_return($result);
    }

    /**
     * @do 客户端---下服务单
     * @param goods_item  json串
     * @param remarks  备注
     * @param science_pics 现场图片
     * @param scienceIds环境配置集合
     * @param appointment_time 预约时间
     * @param address_id 预约地址id
     * @return json
     */
    public function orderService()
    {
        $data = input('post.');
        //        $data['goods_items'] = '[{"id":1,"goods_name":"四柱举升机","b_name":"螺杆机配套设备","type_model":"23232","diagnostic_results":"1111","optionList":[{"oid":1,"content":"11","selected":0},{"oid":3,"content":"3213","selected":0}]},{"id":4,"goods_name":"举升机","b_name":"TANKSTORM汽修工具车","type_model":"wrw","diagnostic_results":"1111","optionList":[{"oid":6,"content":"发动机","selected":0},{"oid":7,"content":"油路","selected":0}]}]';
        $equipment_validate = validate('equipment');
        if (!$equipment_validate->scene('orderService')->check($data)) {
            return json_fail_return($equipment_validate->getError());
        }
        $memberName = $this->user_info['member_name'];
        $memberId = $this->user_id;

        //获取预约地址详细信息
        $address_info = db('address')->where(['address_id' => $data['address_id']])->find();

        // 1.下服务单
        $orderData = array(
            'order_sn' => $this->makeOrderSn(),
            'order_type' => $data['order_type'],
            'member_id' => $memberId,
            'member_name' => $memberName,
            'appointment_time' => $data['appointment_time'],
            'appointment_unix_time' => strtotime($data['appointment_time']),
            'add_time' => time(),
            'update_time' => time(),
            'remarks' => $data['remarks'],
            'address_id' => $data['address_id'],
            'appoint_phone' => $address_info['address_tel_phone'],
            'appoint_address' => $address_info['area_info'],
            'appoint_detail_address' => $address_info['address_detail'],
            'appoint_city' => $address_info['city_id'],
            'appoint_district' => $address_info['area_id'],
        );
        $orderId = db('s_order')->insertGetId($orderData);

        //2.服务单详情单
        $goodsItems = json_decode(htmlspecialchars_decode($data['goods_items']), true);
        foreach ($goodsItems as $goodsItem) {

            $detailInfo = array(
                'order_id' => $orderId,
                'goods_id' => $goodsItem['id'],
                'goods_name' => $goodsItem['goods_name'],
                'b_name' => $goodsItem['b_name'],
                'type_model' => $goodsItem['type_model'],
                'add_time' => time(),
                'scienceIds' => $goodsItem['scienceIds'],
                'diagnostic_cause' => $goodsItem['diagnostic_cause']
            );
            //如果是维修单，并且传了诊断结果
            if ($data['order_type'] == 2 && isset($goodsItem['diagnostic_results'])) {
                $detailInfo['diagnostic_results'] = $goodsItem['diagnostic_results'];
            }
            //如果是维修单保养单可以选择部位，移机单选择拆机和安装这部分统一按照部位存储json串进optionCheckInfo
            if (in_array($data['order_type'], [2, 3, 4]) && isset($goodsItem['optionList']) && $goodsItem['optionList']) {
                $detailInfo['option_info'] = json_encode($goodsItem['optionList']);
            }

            $detailInfo['place_type'] = 1; #选择设备

            #判断是手动添加还是选择设备
            if ($goodsItem['id'] == 0) {
                $detailInfo['place_type'] = 0; #录入设备
                #手动添加
                //处理分类
                $class = db('goodsclass')->where(['gc_id' => $goodsItem['goods_class']])->find();
                if (empty($class['gc_parent_id'])) {
                    //没父值的话就是一级分类id
                    $detailInfo['gc_one_id'] = $class['gc_id'];
                    $detailInfo['gc_id'] = $class['gc_id'];
                    $detailInfo['class_name'] = $class['gc_name'];
                } else {
                    //有父值的话再往上找
                    $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
                    if (empty($class_one['gc_parent_id'])) {
                        $detailInfo['gc_one_id'] = $class_one['gc_id'];
                        $detailInfo['gc_two_id'] = $class['gc_id'];
                        $detailInfo['gc_id'] = $class['gc_id'];
                        $detailInfo['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
                    } else {
                        $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                        $detailInfo['gc_one_id'] =  $class_two['gc_id'];
                        $detailInfo['gc_two_id'] =  $class_one['gc_id'];
                        $detailInfo['gc_three_id'] = $class['gc_id'];
                        $detailInfo['gc_id'] = $class['gc_id'];
                        $detailInfo['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
                    }
                }
            }

            #拆移机类型
            if ($data['order_type'] == 3) {
                $detailInfo['disma_status'] = $goodsItem['disma_status'];
            }

            $detailId = db('s_order_detail')->insertGetId($detailInfo);
            if (!$detailId) {
                return json_fail_return('服务单辅助单生成失败！');
            }

            //3.服务单图片记录存储
            if (isset($goodsItem['science_pics']) && $goodsItem['science_pics']) {
                $pic = array(
                    'order_detail_id' => $detailId,
                    'src' => $goodsItem['science_pics']
                );
                $status = db('s_order_image')->insert($pic);
                if (!$status) {
                    return json_fail_return('服务单图片地址保存失败！');
                }
            }
        }

        return json_success_return(['order_id' => $orderId], '服务预约申请成功');
    }



    /**
     * @title 客户端---追加设备订单
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/get_append_sorder
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_append_sorder()
    {

        $data = input('post.');

        //当前订单的主单id
        $service_id = input('post.service_id');
        $memberId = $this->user_id;
        $memberName = $this->user_info['member_name'];

        if (empty($service_id)) {
            return json_fail_return('参数错误');
        }

        $equipmentModel = new EquipmentModel();
        $result = $equipmentModel->getAppendSorder($data, $service_id, $memberId, $memberName);
        return json_success_return(['order_id' => $result], '服务单追加成功');
    }


    /**
     * @title 客户端---获取服务单 取消订单，更换服务人员，拒单原因
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/get_refusal_reason
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_refusal_reason()
    {
        $RefundreturnModel = new Refundreturn();
        $type = intval(input('post.type'));
        if (empty($type)) {
            return json_fail_return('参数错误');
        }
        $result = $RefundreturnModel->getRefusalReason($type);
        return json_success_return($result);
    }

    /**
     * @title 客户端---更换服务人员接口
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/change_service_personnel
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function change_service_personnel()
    {
        $equipmentModel = new EquipmentModel();
        $data =  input('post.');
        if (empty($data['order_id'])) {
            return json_fail_return('参数错误');
        }
        if (empty($data['refusal_remake'])) {
            return json_fail_return('请填写更换说明');
        }
        $result = $equipmentModel->ChangePersonnel($data, $this->user_id);
        return json_success_return([], '已提交信息，请耐心等候审核');
    }

    /**
     * @title 客户端---服务单  服务完成
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/sorder_completion
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function sorder_completion()
    {
        $equipmentModel = new EquipmentModel();

        $order_id = intval(input('param.order_id'));
        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        $result = $equipmentModel->SorderCompletion($order_id, $this->user_id);
        return json_success_return($result,'服务完成');
    }



    /**
     * @title 客户端---服务单取消订单
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/sorder_cancel
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function sorder_cancel()
    {
        $RefundreturnModel = new Refundreturn();
        //服务单id 和 取消订单原因
        $state_type = input('param.state_type');
        $order_id = intval(input('param.order_id'));
        $cancel_reason = input('param.cancel_reason');
        $cancel_remark = input('param.cancel_remark');

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($cancel_remark)) {
            return json_fail_return('请填写取消说明');
        }

        //获取服务单详情
        $equipmentModel = new EquipmentModel();
        $condition['order_id'] = $order_id;
        $condition['member_id'] = $this->user_id;

        $order_info = $equipmentModel->getEquipmentInfo($condition);

        #下单2小时后不能退单
        $add_time = $order_info['add_time'] + 7200;
        if ($add_time < time()) {
            return json_fail_return('两小时后不可取消订单');
        }
        if (empty($order_info)) {
            return json_fail_return('当前无可操作订单');
        }

        if ($order_info['order_state'] == -1) {
            return json_fail_return('当前操作订单已取消，无需重复操作');
        }

        //判断操作状态
        if ($state_type == 'order_cancel') {
            //取消订单
            $result = $this->_order_cancel($order_info, input('post.'), $order_id, $cancel_reason, $cancel_remark);
        }
        return json_success_return($result);
    }

    /**
     * @title 客户端--获取周围服务人员
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /Equipment/sorder_cancel
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function getAroundService()
    {
        $current_longitude = input('param.longitude'); #经度
        $current_latitude = input('param.latitude');  #纬度

        // $time = date('Y-m-d H:i:s',time());
        // $week = date('w', strtotime($time));
        // $parms['startweek'] = array('<=', $week);
        // $parms['endweek'] = array('>=', $week);

        // $hourMin = date('H:i', strtotime($time));
        // $parms['starttime'] = array('<=', $hourMin);
        // $parms['endtime'] = array('>=', $hourMin);

        // $parms['status'] = 1;
        // $parms['cardstatus'] = 1;
        $parms = [];
        $mers_info = db('fuwu_personal')->where($parms)->select();
        $service_info = [];
        foreach ($mers_info as $k => $v) {
            if (!empty($v['fuwu_longitude'])) {
                $res = $this->getDistance($current_longitude, $current_latitude, $v['fuwu_longitude'], $v['fuwu_latitude']);
                if ($res < 100000000) {
                    $service_info[] = $v;
                }
            }
        }
        return json_success_return($service_info);
    }

    public static function getDistance($lng1, $lat1, $lng2, $lat2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    /**
     * 取消订单
     */
    private function _order_cancel($order_info, $post, $order_id, $cantion_reason, $cancel_remark)
    {
        $equipmentModel = new EquipmentModel();
        return $equipmentModel->changeSorderStateCancel($order_info, 'buyer', $this->user_id, $order_id, $cantion_reason, $cancel_remark);
    }

    private function formateQuestion($levelOne, $questions)
    {
        $levelOne['child'] = [];
        foreach ($questions as $value) {
            if ($value['parent_id'] == $levelOne['id']) {
                $child = $this->formateQuestion($value, $questions);
                $levelOne['child'][] = $child;
            }
        }

        return $levelOne;
    }

    private function makeOrderSn()
    {
        $date = date('Ymd');
        $num = $date . '0000' . substr(time(), 3, 7) . rand(1000, 999);

        return $num;
    }
}
